using System;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Pegasus.Web.UI
{
    /// <summary>
    /// A regular button that allows user to confirm it's click event and/or to redirect them with javascript.
    /// </summary>
    public class ButtonEx : Button
    {
        private string confirmMsg = null;
        private string redirectUrl = null;

        /// <summary>
        /// Sets the confirmation message for the button.
        /// If not set them there is no confirmation message.
        /// </summary>
        public string ConfirmMsg
        {
            set
            {
                confirmMsg = value;
            }
        }

        /// <summary>
        /// Sets the redirect URL for the button.  This must be an absolute Url.
        /// If not set them there is no client side redirection.
        /// </summary>
        public string RedirectUrl
        {
            set
            {
                redirectUrl = value;
            }
        }

		/// <summary>
		/// Raises the <see cref="E:System.Web.UI.Control.Load"></see> event.
		/// </summary>
		/// <param name="e">The <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            StringBuilder sb = new StringBuilder();

            // Add confirmation message if it exists
            if( !string.IsNullOrEmpty( confirmMsg ) )
            {
                sb.AppendFormat( "if( !confirm(\"{0}\")) return false; ", confirmMsg.Replace( '"', '\'' ) );
            }

            // Add redirect Url if it exists (after confirmation message for so it can be confirmed)
            if( !string.IsNullOrEmpty( redirectUrl ) )
            {
                sb.AppendFormat( "window.location='{0}'; return false; ", redirectUrl );
            }

            // Add parts if they existed.
            if( sb.Length > 0 )
            {
                OnClientClick = string.Format( "{0}{1}", sb.ToString(), OnClientClick );
            }
        }
    }
}